
import ARect from './ARect'
import ASize from './ASize'
import dispatch from '../Util/dispatch'

export const Visibility = {
    VISIBLE   : 0x00000000,
    INVISIBLE : 0x00000004,
    GONE      : 0x00000008
}
Object.freeze(Visibility)

export default class AView {

    constructor() {
        this.backgroudColor = undefined
        this.alpha = 1.0
        this._frame = new ARect(0,0,0,0)
        this._subviews = []
        this._superview = undefined
        this._visibility = Visibility.VISIBLE
        this._requestLayout = true
    }

    get frame() : ARect {
        return new ARect(this._frame)
    }

    set frame(frame : ARect) {
        this._frame.x = frame.x
        this._frame.y = frame.y
        this._frame.w = frame.w
        this._frame.h = frame.h
    }

    addSubview(view : AView) {
        this._subviews.push(view)
        this.superview = this
    }

    removeFromSuperview() {
        if(this._superview) {
            let index = this._superview._subviews.indexOf(this)
            if(index >= 0) {
                this._superview._subviews.splice(0,1)
            }
            this._superview = undefined
        }
    }

    get subviews() : Array<AView> {
        return this._subviews.slice(0)
    }

    set superview(view : ?AView) {
        if(this._superview && this._superview != view) {
            this.removeFromSuperview()
        }
        this._superview = view
    }

    get superview() : ?AView {
        return this._superview
    }

    set visibility(mode : number) {
        this._visibility = mode
    }

    get visibility() : number {
        return this._visibility
    }

    draw(context : CanvasRenderingContext2D, rect : ARect) {
        context.save()
        this.onDraw(context, rect)
        this._subviews.map((view) => {
            let frame = view.frame
            frame.x += rect.x
            frame.y += rect.y
            view.draw(context, frame)
        })
        context.restore()
    }

    onDraw(context : CanvasRenderingContext2D, rect : ARect) {
        if(this.backgroudColor) {
            context.beginPath();
            context.rect(rect.x, rect.y, rect.w, rect.h);
            context.fillStyle = this.backgroudColor;
            context.fill();
        }
    }

    set measuredDimensionRaw(measuredSize : ASize) {
        this.measuredSize = Object.assign({}, measuredSize)
    }

    requestLayout() {
        this._requestLayout = true
        if(this.superview) {
            this.superview.requestLayout()
        }
        else if(this.redraw) {
            dispatch.async( ()=> {
                this.redraw(this)
            })
        }
    }

    dealloc() {
        delete this._superview
        delete this._subviews
        delete this.backgroudColor
    }
}
